package com.mdnote.practice.binary_tree;

import java.util.LinkedList;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/9/30
 * @description  填充每个节点的下一个右侧节点指针 II
 */
public class LeetCode117 {
    public Node connect(Node root) {

        if (root == null) {
            return null;
        }
        _bfs(root);
        return root;
    }

    private void _bfs(Node node) {
        LinkedList<Node> queue = new LinkedList<>();
        queue.addLast(node);

        while (!queue.isEmpty()) {
            int size = queue.size();
            Node preNode = null;
            for (int i = 0; i < size; i++) {

                Node curNode = queue.removeFirst();
                if (i == 0) {
                    // 第一个元素
                    preNode = curNode;
                } else {
                    preNode.next = curNode;
                    preNode = curNode;
                }
                if (curNode.left != null) {
                    queue.addLast(curNode.left);
                }
                if (curNode.right != null) {
                    queue.addLast(curNode.right);
                }
            }
        }
    }

    private static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }
}
